import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class UserRoleService extends BaseService<any> {
  private readonly logger = new Logger(UserRoleService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * add
   * 对应 PHP: UserRoleService_admin::add()
   * 逻辑类型: undefined - undefined
   */
  async add(uid: any[], data: any[], site_id: any[]) {
    // 基于PHP真实逻辑: add
    // PHP原文: $user_role_model = new SysUserRole();         $is_exist = $user_role_model->where([ ['uid', '=', $uid], ['site_id', '=', $site_id] ])->count();       ...
const user_role_model = this.sysUserRoleService;
        const is_exist = user_role_model.where([ ['uid', '=', uid], ['site_id', '=', site_id) )).count(];
        if (is_exist) throw new BusinessException('SITE_USER_EXIST'];

        const is_admin = data.is_admin || 0;
        const role_data = [
            uid: uid,
            is_admin: is_admin,
            site_id: site_id == 0 ? this.site_id : site_id,
            status: data.status || UserDict.ON
        );
        if (!is_admin) {
            //校验权限越界
            role_data.role_ids = data.role_ids || [];
  }

  /**
   * edit
   * 对应 PHP: UserRoleService_admin::edit()
   * 逻辑类型: undefined - undefined
   */
  async edit(site_id: any[], uid: any[], role_ids: any[], status: any[]) {
    // 基于PHP真实逻辑: edit
    // PHP原文: $user_role = $this->model->where([['uid', '=', $uid], ['site_id', '=', $site_id]])->findOrEmpty();         if ($user_role->isEmpty())             thro...
const user_role = this.model.where([['uid', '=', uid], ['site_id', '=', site_id))).findOrEmpty(];
        if (user_role.isEmpty())
            throw new AdminBusinessException('NO_SITE_USER_ROLE');

        const is_admin = user_role.is_admin;
        if(is_admin)//超级管理员不允许改动权限
            throw new AdminBusinessException('ADMIN_NOT_ALLOW_EDIT_ROLE');
        user_role.status = status;
        if (!!array_diff_assoc(role_ids, user_role.role_ids))) {
            //校验权限越界
            user_role.role_ids = role_ids;
  }

  /**
   * getUserRole
   * 对应 PHP: UserRoleService_admin::getUserRole()
   * 逻辑类型: undefined - undefined
   */
  async getUserRole(site_id: number, uid: number) {
    // 基于PHP真实逻辑: getUserRole
    // PHP原文: $cache_name = 'user_role_'.$uid.'_'.$site_id;         return cache_remember(             $cache_name,             function() use($uid, $site_id) {    ...
const cache_name = 'user_role_'.uid + '_'.site_id;
        return cache_remember(
            cache_name,
            function() use(uid, site_id) {
                const user_role_model = this.sysUserRoleService;
                const where = [
                    ['uid', '=', uid],
                    ['site_id', '=', site_id)
                ];
                return user_role_model.where(where).findOrEmpty().toArray(];
  }

  /**
   * getUserDefaultSiteId
   * 对应 PHP: UserRoleService_admin::getUserDefaultSiteId()
   * 逻辑类型: undefined - undefined
   */
  async getUserDefaultSiteId(uid: number) {
    // 基于PHP真实逻辑: getUserDefaultSiteId
    // PHP原文: $user_role_model = new SysUserRole();         $default_site_id = $this->request->defaultSiteId();         return $user_role_model->where([['uid', '=',...
const user_role_model = this.sysUserRoleService;
        const default_site_id = this.request.defaultSiteId(];
        return user_role_model.where([['uid', '=', uid], ['site_id', '<>', default_site_id))).findOrEmpty()?.site_id;
    }

    /**
     * 通过角色id组获取角色
     * @param role_ids
     * @param int site_id
     * @return mixed
     */
    async getRoleByUserRoleIds(role_ids, int site_id){
        sort(role_ids);
        const cache_name = 'role_by_ids_'.md5(implode(',', role_ids)) + '_'.site_id;
        return cache_remember(
            cache_name,
            function() use(role_ids, site_id) {
                const where = [
                    ['role_id', 'in', role_ids],
                    ['site_id', '=', site_id],
                    ['status', '=', RoleStatusDict.ON )
                ];
                return SysRole.where(where).column('role_name');
  }

  /**
   * getRoleByUserRoleIds
   * 对应 PHP: UserRoleService_admin::getRoleByUserRoleIds()
   * 逻辑类型: undefined - undefined
   */
  async getRoleByUserRoleIds(role_ids: any[], site_id: any[]) {
    // 基于PHP真实逻辑: getRoleByUserRoleIds
    // PHP原文: sort($role_ids);         $cache_name = 'role_by_ids_'.md5(implode(',', $role_ids)).'_'.$site_id;         return cache_remember(             $cache_nam...
sort(role_ids);
        const cache_name = 'role_by_ids_'.md5(implode(',', role_ids)) + '_'.site_id;
        return cache_remember(
            cache_name,
            function() use(role_ids, site_id) {
                const where = [
                    ['role_id', 'in', role_ids],
                    ['site_id', '=', site_id],
                    ['status', '=', RoleStatusDict.ON )
                ];
                return SysRole.where(where).column('role_name');
  }

  /**
   * editAdmin
   * 对应 PHP: UserRoleService_admin::editAdmin()
   * 逻辑类型: undefined - undefined
   */
  async editAdmin(site_id: number, uid: number) {
    // 基于PHP真实逻辑: editAdmin
    // PHP原文: $user_role = $this->model->where([['is_admin', '=', 1], ['site_id', '=', $site_id]])->findOrEmpty();         if ($user_role->isEmpty())             th...
const user_role = this.model.where([['is_admin', '=', 1], ['site_id', '=', site_id))).findOrEmpty(];
        if (user_role.isEmpty())
            throw new AdminBusinessException('USER_NOT_EXIST'];
        user_role.uid = uid;
        user_role.save(];
        Cache.delete('user_role_'.uid + '_'.site_id];
        Cache.delete('user_role_list_' .uid);
        return true;
    }


}
  }
}
